/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ManagementService;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.db.ListQueryParameterObject;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.interceptor.CommandExecutor;
import com.je.bpm.engine.query.Query;
import com.je.bpm.engine.query.QueryProperty;

import java.io.Serializable;
import java.util.List;

/**
 * Abstract superclass for all query types.
 * 所有封装查询的抽象实现，都需要继承此类
 */
public abstract class AbstractQuery<T extends Query<?, ?>, U> extends ListQueryParameterObject implements Command<Object>, Query<T, U>, Serializable {

    private static final long serialVersionUID = 1L;

    public static final String SORTORDER_ASC = "asc";
    public static final String SORTORDER_DESC = "desc";

    private static enum ResultType {
        LIST, LIST_PAGE, SINGLE_RESULT, COUNT
    }

    protected transient CommandExecutor commandExecutor;
    protected transient CommandContext commandContext;

    protected String databaseType;

    protected String orderBy;

    protected ResultType resultType;

    protected QueryProperty orderProperty;

    public static enum NullHandlingOnOrder {
        NULLS_FIRST, NULLS_LAST
    }

    protected NullHandlingOnOrder nullHandlingOnOrder;

    protected AbstractQuery() {
        parameter = this;
    }

    protected AbstractQuery(CommandExecutor commandExecutor) {
        this.commandExecutor = commandExecutor;
    }

    public AbstractQuery(CommandContext commandContext) {
        this.commandContext = commandContext;
    }

    // To be used by custom queries
    public AbstractQuery(ManagementService managementService) {
        this(((ManagementServiceImpl) managementService).getCommandExecutor());
    }

    public AbstractQuery<T, U> setCommandExecutor(CommandExecutor commandExecutor) {
        this.commandExecutor = commandExecutor;
        return this;
    }

    @Override
    public T orderBy(QueryProperty property) {
        this.orderProperty = property;
        return (T) this;
    }

    public T orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
        orderBy(property);
        this.nullHandlingOnOrder = nullHandlingOnOrder;
        return (T) this;
    }

    @Override
    public T asc() {
        return direction(Direction.ASCENDING);
    }

    @Override
    public T desc() {
        return direction(Direction.DESCENDING);
    }

    public T direction(Direction direction) {
        if (orderProperty == null) {
            throw new ActivitiIllegalArgumentException("You should call any of the orderBy methods first before specifying a direction");
        }
        addOrder(orderProperty.getName(), direction.getName(), nullHandlingOnOrder);
        orderProperty = null;
        nullHandlingOnOrder = null;
        return (T) this;
    }

    protected void checkQueryOk() {
        if (orderProperty != null) {
            throw new ActivitiIllegalArgumentException("Invalid query: call asc() or desc() after using orderByXX()");
        }
    }

    @Override
    public U singleResult() {
        this.resultType = ResultType.SINGLE_RESULT;
        if (commandExecutor != null) {
            return (U) commandExecutor.execute(this);
        }
        return executeSingleResult(Context.getCommandContext());
    }

    @Override
    public List<U> list() {
        this.resultType = ResultType.LIST;
        if (commandExecutor != null) {
            return (List<U>) commandExecutor.execute(this);
        }
        return executeList(Context.getCommandContext(), null);
    }

    @Override
    public List<U> listPage(int firstResult, int maxResults) {
        this.firstResult = firstResult;
        this.maxResults = maxResults;
        this.resultType = ResultType.LIST_PAGE;
        if (commandExecutor != null) {
            return (List<U>) commandExecutor.execute(this);
        }
        return executeList(Context.getCommandContext(), new Page(firstResult, maxResults));
    }

    @Override
    public long count() {
        this.resultType = ResultType.COUNT;
        if (commandExecutor != null) {
            return (Long) commandExecutor.execute(this);
        }
        return executeCount(Context.getCommandContext());
    }

    @Override
    public Object execute(CommandContext commandContext) {
        if (resultType == ResultType.LIST) {
            return executeList(commandContext, null);
        } else if (resultType == ResultType.SINGLE_RESULT) {
            return executeSingleResult(commandContext);
        } else if (resultType == ResultType.LIST_PAGE) {
            return executeList(commandContext, null);
        } else {
            return executeCount(commandContext);
        }
    }

    public abstract long executeCount(CommandContext commandContext);

    /**
     * Executes the actual query to retrieve the list of results.
     *
     * @param page used if the results must be paged. If null, no paging will be applied.
     */
    public abstract List<U> executeList(CommandContext commandContext, Page page);

    public U executeSingleResult(CommandContext commandContext) {
        List<U> results = executeList(commandContext, null);
        if (results.size() == 1) {
            return results.get(0);
        } else if (results.size() > 1) {
            throw new ActivitiException("Query return " + results.size() + " results instead of max 1");
        }
        return null;
    }

    protected void addOrder(String column, String sortOrder, NullHandlingOnOrder nullHandlingOnOrder) {
        if (orderBy == null) {
            orderBy = "";
        } else {
            orderBy = orderBy + ", ";
        }

        String defaultOrderByClause = column + " " + sortOrder;

        if (nullHandlingOnOrder != null) {
            if (nullHandlingOnOrder.equals(NullHandlingOnOrder.NULLS_FIRST)) {
                if (ProcessEngineConfigurationImpl.DATABASE_TYPE_H2.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_HSQL.equals(databaseType)
                        || ProcessEngineConfigurationImpl.DATABASE_TYPE_POSTGRES.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_ORACLE.equals(databaseType)) {
                    orderBy = orderBy + defaultOrderByClause + " NULLS FIRST";
                } else if (ProcessEngineConfigurationImpl.DATABASE_TYPE_MYSQL.equals(databaseType)) {
                    orderBy = orderBy + "isnull(" + column + ") desc," + defaultOrderByClause;
                } else if (ProcessEngineConfigurationImpl.DATABASE_TYPE_DB2.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_MSSQL.equals(databaseType)) {
                    orderBy = orderBy + "case when " + column + " is null then 0 else 1 end," + defaultOrderByClause;
                } else {
                    orderBy = orderBy + defaultOrderByClause;
                }

            } else if (nullHandlingOnOrder.equals(NullHandlingOnOrder.NULLS_LAST)) {

                if (ProcessEngineConfigurationImpl.DATABASE_TYPE_H2.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_HSQL.equals(databaseType)
                        || ProcessEngineConfigurationImpl.DATABASE_TYPE_POSTGRES.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_ORACLE.equals(databaseType)) {
                    orderBy = orderBy + column + " " + sortOrder + " NULLS LAST";
                } else if (ProcessEngineConfigurationImpl.DATABASE_TYPE_MYSQL.equals(databaseType)) {
                    orderBy = orderBy + "isnull(" + column + ") asc," + defaultOrderByClause;
                } else if (ProcessEngineConfigurationImpl.DATABASE_TYPE_DB2.equals(databaseType) || ProcessEngineConfigurationImpl.DATABASE_TYPE_MSSQL.equals(databaseType)) {
                    orderBy = orderBy + "case when " + column + " is null then 1 else 0 end," + defaultOrderByClause;
                } else {
                    orderBy = orderBy + defaultOrderByClause;
                }

            }

        } else {
            orderBy = orderBy + defaultOrderByClause;
        }

    }

    @Override
    public String getOrderBy() {
        if (orderBy == null) {
            return super.getOrderBy();
        } else {
            return orderBy;
        }
    }

    @Override
    public String getOrderByColumns() {
        return getOrderBy();
    }

    @Override
    public String getDatabaseType() {
        return databaseType;
    }

    @Override
    public void setDatabaseType(String databaseType) {
        this.databaseType = databaseType;
    }

}
